﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AttributeRouting;
using AttributeRouting.Web.Mvc;
using Newtonsoft.Json.Linq;

using Invoicing.Model.Results;
using Invoicing.Model.Orders;
using Invoicing.Logic.Orders;
using Invoicing.Model.Views;
using Invoicing.Logic.Views;
namespace Invoicing.Web.Management.Areas.Orders.Controllers
{
    [RouteArea("Orders")]
    [RoutePrefix("ProductOrder")]
    [Authorize]
    public class ProductOrderApiController : ApiController
    {
        [Route("SaveOrders")]
        [HttpPost]
        public JsonEntity<ProductOrderModel> SaveOrders(JObject request)
        {
            string errinfo = "对不起！单据保存失败，出错原因：";
            try
            {
                #region 收集参数
                var order = new ProductOrderModel() { Items = new ProductOrderDetailCollection() };
                var items = request.GetValue("orderItems");
                if (items != null)
                {
                    order.AssociatedDealID = request.Value<int?>("dealOrderID");
                    order.NoteDate = request.Value<DateTime>("orderDate");
                    order.HouseID = request.Value<int>("houseID");
                    order.OperatorUserID = Web.Global.WebContext.CurrentUser.ID;
                    order.Method = request.Value<int>("method");
                    foreach (var it in items)
                    {
                        order.Items.Add(new ProductOrderDetailModel()
                        {
                            ProductID = it.Value<int>("productID"),
                            MaterialID = it.Value<int>("materialID"),
                            ProcessID = it.Value<int>("processID"),
                            CostMoney = it.Value<decimal>("costMoney"),
                            Quantity = it.Value<decimal>("quantity"),
                            Size = it.Value<string>("size")
                        });
                    }
                }
                else
                    throw new Utils.InvoicingException("没有单据内容。");
                
                #endregion

                var ret = ProductOrderLogic.NewOrder(order);
                return new JsonEntity<ProductOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo += lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<ProductOrderModel>(null, errinfo, false);
        }
        [Route("GetOrders")]
        [HttpPost]
        public JsonEntitySet<ProductOrderModel> GetOrders(JObject request)
        {
            string errinfo = "no data";
            try
            {
                #region 收集参数
                ProductOrderQuery sea = new ProductOrderQuery();
                sea.PageSize = request.Value<int>("pageSize");
                sea.PageIndex = request.Value<int>("pageIndex");
                sea.GetCustomer = request.Value<bool>("getCustomer");
                sea.GetHouse = request.Value<bool>("getHouse");
                sea.CustomerID = request.Value<int>("customerID");
                sea.HouseID = request.Value<int>("houseID");
                sea.OrderNo = request.Value<string>("orderNo");
                sea.GetOperator = request.Value<bool>("getOperator");
                var odb = request.Value<string>("orderDateBefore");
                if (!string.IsNullOrEmpty(odb))
                    sea.OrderDateBefore = DateTime.Parse(odb);
                var oda = request.Value<string>("orderDateAfter");
                if (!string.IsNullOrEmpty(oda))
                    sea.OrderDateAfter = DateTime.Parse(oda);
                sea.Method = request.Value<int>("method");
                sea.GetDealOrder = request.Value<bool>("getDealOrder");
                #endregion

                var ret = ProductOrderLogic.GetOrders(sea);
                return new JsonEntitySet<ProductOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntitySet<ProductOrderModel>(null, errinfo, false);
        }
        [Route("SetBalance")]
        [HttpPost]
        public JsonEntity<ProductOrderModel> SetBalance(JObject request)
        {
            string errinfo = "对不起！单据保存失败，出错原因：";
            try
            {
                #region 收集参数
                var order = new ProductOrderModel() { Items = new ProductOrderDetailCollection() };
                var items = request.GetValue("orderItems");
                if (items != null)
                {
                    order.NoteDate = request.Value<DateTime>("orderDate");
                    order.HouseID = 1;
                    order.OperatorUserID = Web.Global.WebContext.CurrentUser.ID;
                    order.Method = request.Value<int>("orderMethod");
                    order.Description = request.Value<string>("description");
                    order.HouseID = request.Value<int>("houseID");
                    foreach (var it in items)
                    {
                        order.Items.Add(new ProductOrderDetailModel()
                        {
                            ProductID = it.Value<int>("productID"),
                            MaterialID = it.Value<int>("materialID"),
                            ProcessID = it.Value<int>("processID"),
                            Quantity = it.Value<decimal>("quantity"),
                            Size = it.Value<string>("size")
                        });
                    }
                }
                else
                    throw new Utils.InvoicingException("没有单据内容。");
                #endregion

                var ret = ProductOrderLogic.SetBalance(order);
                return new JsonEntity<ProductOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo += lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<ProductOrderModel>(null, errinfo, false);
        }
        [Route("GetViewOrders")]
        [HttpPost]
        public JsonEntitySet<ViewProductOrderModel> GetViewOrders(JObject request)
        {
            string errinfo = "no data";
            try
            {
                #region 收集参数
                ViewProductOrderQuery sea = new ViewProductOrderQuery();
                sea.PageSize = request.Value<int>("pageSize");
                sea.PageIndex = request.Value<int>("pageIndex");
                sea.ProductID = request.Value<int>("productID");
                sea.MaterialID = request.Value<int>("materialID");
                sea.ProcessID = request.Value<int>("processID");
                sea.Size = request.Value<string>("size");
                sea.OrderNo = request.Value<string>("orderNo");
                sea.PType = request.Value<byte>("ptype");
                sea.HouseID = request.Value<int>("houseID");

                var odb = request.Value<string>("orderDateBefore");
                if (!string.IsNullOrEmpty(odb))
                    sea.OrderDateBefore = DateTime.Parse(odb);
                var oda = request.Value<string>("orderDateAfter");
                if (!string.IsNullOrEmpty(oda))
                    sea.OrderDateAfter = DateTime.Parse(oda);
                var orderMethod = request.Value<string>("orderMethod");
                if (!string.IsNullOrEmpty(orderMethod))
                    sea.Method = orderMethod.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                #endregion

                var ret = ViewProductOrderLogic.Gets(sea);
                return new JsonEntitySet<ViewProductOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntitySet<ViewProductOrderModel>(null, errinfo, false);
        }
    }
}
